import java.util.*;

//Definition for a binary tree node.
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode() {}
    TreeNode(int val) { this.val = val; }
    TreeNode(int val, TreeNode left, TreeNode right) {
       this.val = val;
       this.left = left;
       this.right = right;
    }
}

class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ret = new ArrayList<>();
        if(root == null){
            return ret;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        boolean flag = true;
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            while(size > 0){
                TreeNode node = queue.poll();
                list.add(node.val);
                if(node.left != null){
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
                size--;
            }
            if(!flag){
                reverse(list);
                //Collections.reverse(list);
            }
            ret.add(list);
            flag = (!flag);
        }
        return ret;
    }
    private void reverse(List<Integer> list){
        int left = 0;
        int right = list.size() - 1;
        while(left < right){
            swap(list, left, right);
            left++;
            right--;
        }
    }
    private void swap(List<Integer> list, int left, int right){
        int num = list.get(left);
        list.set(left, list.get(right));
        list.set(right, num);
    }
}